<?php
/**
 * PHP-DI + Slim 4 注解注入完整示例（修复属性注入为null问题）
 * 功能：通过@Inject注解自动注入DatabaseService到UserController
 * 使用说明：
 * 1. 确保已安装依赖：composer require php-di/slim-bridge:3.4 php-di/php-di:6.4 doctrine/annotations:2.0 slim/slim:4.* slim/psr7:^1.6
 * 2. 启动服务：composer start（需在composer.json中配置"start": "php -S localhost:8080 -t public"）
 * 3. 访问测试：http://localhost:8080/users
 */
require_once __DIR__ . '/../vendor/autoload.php';

// 初始化日志函数
function logMessage($message)
{
    $time = date('[Y-m-d H:i:s]');
    $logContent = "{$time} [DI-Slim Debug] {$message}";
    error_log($logContent);
    // echo "{$time} [DI Debug] {$message}<br>"; // 同时输出到浏览器
    // echo nl2br($logContent . "\n");
}

// 1. 定义依赖服务类
class DatabaseService
{
    public function __construct()
    {
    }

    public function getConnection(): string
    {
        return 'MySQL 数据库连接';
    }
}

// 2. 定义控制器类
class UserController
{
    /**
     * @Inject // 关键：声明需要自动注入
     * @var DatabaseService // 关键：指定注入的依赖类型
     */
    private $db;

    public function __construct()
    {
    }

    public function index($request, $response)
    {

        if ($this->db === null || !($this->db instanceof DatabaseService)) {
            $errorMsg = "UserController->index() - db属性为null，注入失败, 类型: " . gettype($this->db) . '---';
            logMessage($errorMsg);
            throw new \RuntimeException($errorMsg);
        }
        $connectionInfo = $this->db->getConnection();
        $response->getBody()->write(json_encode([
            'code' => 200,
            'message' => '请求成功',
            'data' => [
                'connection_info' => $connectionInfo,
                'timestamp' => time()
            ]
        ], JSON_UNESCAPED_UNICODE));
        return $response->withHeader('Content-Type', 'application/json');
    }
}

// 3. 引入必要的命名空间
use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;
// use Slim\Factory\AppFactory;
use DI\Bridge\Slim\Bridge as SlimBridge;


// 4. 初始化容器构建器,启用自动装配
$containerBuilder = new ContainerBuilder();
$containerBuilder->useAutowiring(true);
$containerBuilder->useAnnotations(true);

try {
    /** @var ContainerInterface $container  */
    $container = $containerBuilder->build();
    $app = SlimBridge::create($container);
} catch (\Exception $e) {
    logMessage("初始化失败: " . $e->getMessage() . " 在 " . $e->getFile() . " 行: " . $e->getLine());
    die("初始化失败: " . $e->getMessage());
}

// 8. 定义路由
$app->get('/users', function ($request, $response) use ($container) {
    $controller = $container->get(UserController::class);
    return $controller->index($request, $response);
});

$app->run();
?>